import cPickle as Pickle
import os,socket,time,re,subprocess,hashlib
import Exceptions
import pwd,getpass

#Mettre des exceptions
def check_root():
    pw = pwd.getpwnam(getpass.getuser())
    uid = pw.pw_uid
    if uid == 0:
        return True
    else:
        return False
    
def save(object,path):
    ''''save the gived object in the gived path using pickle'''
    
    path,filename = os.path.split(path)
    if not os.path.exists(path):
        print "path %s does not exist" % (path,)
        print "will now create %s" % (path,)
        os.makedirs(path)
    file_path = os.path.join(path,filename)
    file = open(file_path,'w')
    Pickle.dump(object,file,True)
    file.close()
    os.chmod(file_path, 700)
    
def load(path):
    '''try to load the object stored in the gived path using pickle'''
    
    try:
        file = open(path, 'r')
        object = Pickle.load(file)
        return object
    except Exception, e:
        print "could not load %s" % (path,)

def get_host_latency(host,port):
    """return remote service latency in ms or an 2-tuple error"""
    try:
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.settimeout(1) # set a one second timeout
        start = time.time()
        sock.connect((host,port))
        end = time.time()
        sock.close()
        return int(( end - start ) * 1000)
    except socket.error, error:
        return error
    
def get_default_route():
    cmd_result = os.popen('ip route | grep default').read()
    if len(cmd_result):
        cmd_result = cmd_result.split(' ')
        next_item = None
        gateway = None
        for item in cmd_result:
            if next_item == 'via':
                gateway = item
                next_item = None
            elif next_item == 'dev':
                interface = item
                next_item = None
            if item == 'via':
                next_item = 'via'
            elif item == 'dev':
                next_item = 'dev'
        return interface,gateway
    return None,None

def get_interface_info(interface):
    if interface:
        cmd_result = os.popen('ifconfig ' + interface).read()
        REGEX_IFCONFIG = '^(.*:(\d{1,3}(\.)?){4}){3}$'
        ip = None
        mask = None
        bcast = None
        for line in cmd_result.split('\n'):
            if re.match(REGEX_IFCONFIG,line):
                if len(line):
                    try:
                        ip,mask,bcast =  [ item.split(':')[1].rstrip('\n') for item in line.split(' ') if item.find(':') != -1]
                    except:
                        print 'Cant parse ifconfig !!!'
        return ip,mask,bcast

def get_public_addr():
    """Return net ip addr"""
    from urllib2 import urlopen
    try:
        ip =  urlopen("http://www.whatismyip.com/automation/n09230945.asp").read()
    except:    
        return None
    if re.match("^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$",ip):
        return ip

def get_addr_by_name(hostname):
    try:
        return socket.gethostbyname(hostname)
    except:
        return None

def get_mtab():
    """ return a splited line by line mtab copy """
    # tab : [ filesystem, mount point, type, options, dump, pass ]
    # TODO --> row filter to avoid threat /dev or /proc each time
    mtab = open('/etc/mtab','r')
    tab = [ line.rstrip('\n').split(' ') for line in mtab ]    
    mtab.close()
    return tab

def check_mount_point(path):
    """ check a mount_point """
    if not os.path.exists(path):
        raise Exceptions.DirNotFoundException(path)
    if len(os.listdir(path)) > 0:
        raise Exceptions.DirIsNotEmptyException(path)

def check_host_pub_key(share):
    cmd = ['ssh-keyscan','-H',share.server]
    getkey = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    stdout,stderr = getkey.communicate()
    key = stdout.split('ssh-rsa')[1].strip('\n').strip(' ')

    if not len(key):
        raise Exceptions.CantGetHostPubKey(share)

    ### Get the already known keys
    try:
        known_keys = set([item.split('ssh-rsa')[1].strip('\n').strip(' ') for item in open('/root/.ssh/known_hosts','r').readlines()]) ### NASTY /root/... hard codded
    except:
        known_keys = set()
    
    if not key in known_keys:
        raise Exceptions.UnknownHostPubKey(share,stdout)
    
    return True

def add_host_pub_key(key,path):
    path,file = os.path.split(path)
    if not os.path.isdir(path):
        create_directory(path)
    print os.path.join(path,file)
    output_file = open(os.path.join(path,file),'a')
    output_file.write(key)
    output_file.close()
    
def mount(share):
    """ mount a share """
    cmd = share.build_mount_cmd()
    print cmd
    
    mount = subprocess.Popen(cmd,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ,shell=False)
    
    if share.protocol == 'SSH':
        mount.stdin.write(share.password)
    
    stdout,stderr = mount.communicate()
    
    print stdout
    print stderr
    
    if stdout.find('mount error(6): No such device or address') != -1:
        raise Exceptions.SharePathUnreachable(share)
    elif stdout.find('mount error 6 = No such device or address') != -1:
        raise Exceptions.RemoteDirNotFound(share)
    elif stdout.find('mount error 13 = Permission denied') != -1:
        raise Exceptions.PermissionDenied(share)
    elif stderr.find('read: Connection reset by peer') != -1:
        raise Exceptions.InvalidLogin(share)
    elif stderr.find('No such file or directory') != -1:
        raise Exceptions.RemoteDirNotFound(share)
    
def unmount(item):
    if isinstance(item,str):
        cmd = ('umount',item)
    else:
        cmd = ('umount',item.mount_label)
    umount = subprocess.Popen(cmd,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
    stdout,stderr = umount.communicate()
    
def create_directory(path):
    if not os.path.isdir(path):
        os.makedirs(path)

def remove_directory(path):
    if os.path.isdir(path):
        try:
            os.rmdir(path)
        except:
            pass

def xdg_open(path):
    cmd = ('gnome-open',path)
    xdg = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
def get_smb_shares(server,user=None):
    if isinstance(get_host_latency(server, 139),int):
        cmd = ('smbclient','-N', '-L' + server)
        proc = subprocess.Popen(cmd,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
        stdout,stderr = proc.communicate()
        for line in [lines for lines in stdout.split('\n') if lines.find('Disk')!= -1 and lines.find('$') == -1]:
            return [ item.strip('\t') for item in line.split(' ') if item != '' and item != 'Disk']

if __name__ == "__main__":
#    save(["prout",{"prout2":0,"prout3":"kk"},(0,['a','b','c'])],"/tmp/bandoine/prout.pkl")
#    print load("/tmp/bandoine/prout.pkl")
#    print isinstance(get_host_latency('bandoine.fr', 21),Exception)
#    print socket.gethostaddr()
#    get_default_route()[0]
#    print get_remote_addr()
#    print get_addr_by_name('bandoine.fr')
#    print get_interface_info('wlan0')
#    print get_mtab()
#    check_mount_point('/mnt/kiki/')
#    mount("prout")
    print get_smb_shares('192.168.0.12')